package com.doudou.collection.domain.service.admin.impl;


import com.doudou.collection.dao.mapper.admin.SysMenuMapper;
import com.doudou.collection.domain.service.admin.SysMenuService;
import com.doudou.collection.infrastructure.common.pojo.vo.TreeSelect;
import com.doudou.collection.infrastructure.common.security.SecurityUtils;
import com.doudou.collection.orm.entity.admin.SysUser;
import com.doudou.collection.orm.vo.admin.MenuOptionsVO;
import com.doudou.collection.orm.vo.admin.MetaVo;
import com.doudou.collection.orm.vo.admin.RouterVO;
import com.doudou.collection.orm.vo.admin.SysMenuListVO;
import com.doudou.collection.utils.StringUtils;
import com.doudou.collection.utils.UserConstants;
import com.doudou.collection.utils.text.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName SysMenuServiceImpl<br>
 * @Description 菜单 业务层实现类<br>
 * @Author 李浩文<br>
 * @Date 2023/6/27 17:34<br>
 * @Version 1.0<br>
 */
@Slf4j
@Service
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<RouterVO> buildMenus(List<SysMenuListVO> menus) {
        List<RouterVO> routers = new LinkedList<RouterVO>();
        for (SysMenuListVO menu : menus) {
            RouterVO router = new RouterVO();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache().toString()), menu.getPath()));
            List<SysMenuListVO> cMenus = menu.getChildren();
            if (StringUtils.isNotEmpty(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVO> childrenList = new ArrayList<RouterVO>();
                RouterVO children = new RouterVO();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache().toString()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVO> childrenList = new ArrayList<RouterVO>();
                RouterVO children = new RouterVO();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenuListVO menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenuListVO menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenuListVO menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{Constants.HTTP, Constants.HTTPS, Constants.WWW, "."},
                new String[]{"", "", "", "/"});
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenuListVO menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenuListVO menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenuListVO menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }



    @Override
    public List<SysMenuListVO> listMenuTreeByUserId(Long userId) {
        List<SysMenuListVO> menus = null;
        if (SecurityUtils.isAdmin(userId)) {
            menus = sysMenuMapper.selectMenuTreeAll();
        } else {
            menus = sysMenuMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

    @Override
    public List<SysMenuListVO> listMenuOptions(Long userId) {
        List<SysMenuListVO> menuList = null;
        if (SecurityUtils.isAdmin(userId)) {
            menuList = sysMenuMapper.listMenuOptions();
        } else {
            menuList = sysMenuMapper.listMenuOptionsByUserId(userId);
        }
        return menuList;
    }

    @Override
    public List<SysMenuListVO> buildMenuTree(List<SysMenuListVO> list) {
        List<SysMenuListVO> menuList = new ArrayList<>();
        List<Long> tempList = list.stream().map(SysMenuListVO::getMenuId).collect(Collectors.toList());
        for (SysMenuListVO menu : list) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(list, menu);
                menuList.add(menu);
            }
        }
        if (menuList.isEmpty()) {
            menuList = list;
        }
        return menuList;
    }

    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<SysMenuListVO> list) {
        List<SysMenuListVO> menuTrees = buildMenuTree(list);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据父节点的ID获取所有子节点
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return
     */
    public List<SysMenuListVO> getChildPerms(List<SysMenuListVO> list, int parentId) {
        List<SysMenuListVO> returnList = new ArrayList<>();
        for (SysMenuListVO m : list) {
            if (m.getParentId() == parentId) {
                recursionFn(list, m);
                returnList.add(m);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     * @param list
     * @param child
     */
    private void recursionFn(List<SysMenuListVO> list, SysMenuListVO child) {
        // 得到子节点列表
        List<SysMenuListVO> childList = getChildList(list, child);
        child.setChildren(childList);
        for (SysMenuListVO c : childList) {
            if (hasChild(list, c)) {
                recursionFn(list, c);
            }
        }
    }


    /**
     * 得到子节点列表
     * @param list 所有菜单列表
     * @param parentNode 父菜单
     * @return 子菜单列表
     */
    private List<SysMenuListVO> getChildList(List<SysMenuListVO> list, SysMenuListVO parentNode) {
        List<SysMenuListVO> childList = new ArrayList<>();
        // 遍历所有菜单
        for (SysMenuListVO childNode : list) {
            // 判断菜单的父菜单id是否和当前传入的父菜单id相等
            if (childNode.getParentId().longValue() == parentNode.getMenuId().longValue()) {
                // 相等就添加到子菜单列表中
                childList.add(childNode);
            }
        }
        return childList;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenuListVO> list, SysMenuListVO m) {
        return getChildList(list, m).size() > 0;
    }
}













